package controllers;

import models.*;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import play.*;
import play.libs.Mail;
import play.mvc.*;

import java.text.DateFormat;
import java.util.List;
import java.util.Locale;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;


public class Absence extends CRUD {
    public static void absences() throws EmailException {
        String[] absents = params.getAll("absent");
        for(String abs : absents){
            models.Utilisateur absent = models.Utilisateur.find("byId", Long.parseLong(abs)).first();
            models.Sceance sc = models.Sceance.find("byId", Long.parseLong(params.get("sceance"))).first();
            models.Absence absence = new models.Absence(absent, sc);
            absence.save();

            List<models.Absence> absences = models.Absence.find("byEleve", absent).fetch();
            
            // email conf
            String to = absent.getEmail();
            String from = "secretariat-test@iut.univ-paris8.fr";
            
            Properties properties = System.getProperties();
            properties.put("mail.smtp.host", "smtp.gmail.com");
            properties.put("mail.smtp.starttls.enable", "true");
            properties.put("mail.smtp.auth", "true");
            properties.put("mail.debug", "true");
            properties.put("mail.store.protocol", "pop3");
            properties.put("mail.transport.protocol", "smtp");
            final String username = "csid2013c@gmail.com";
            final String password = "testeur1";
            Session session = Session.getDefaultInstance(properties,
                    new Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(username, password);
                        }
                    });        
            
            if(absences.size() > 10){
            	
                try{
                    MimeMessage message = new MimeMessage(session);
                    message.setFrom(new InternetAddress(from));
                    message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(to));
                    message.setSubject("Limite d'absence bientot atteinte");

                    message.setContent("Bonjour " + absent.getNom() + " " + absent.getPrenom() + ", Vous approchez de la limite des 15 heures d'absence.\nFaites attention, nous vous rappellons que toute absence doit etre justifiee et peux entrainer des sanctions pouvant aller jusqu'a la non obtention du diplome en cours.", "text/html" );

                    // Send message
                    Transport.send(message);
                    
                 }catch (MessagingException mex) {
                    mex.printStackTrace();
                 }
            }
            
            String dateConverted;
            Locale locale = Locale.getDefault();
            DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, locale);
            dateConverted =  dateFormat.format(sc.getDebut());
            
            try{
                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(from));
                message.addRecipient(Message.RecipientType.TO,
                new InternetAddress(to));
                message.setSubject("Une nouvelle absence a été signalée");

                message.setContent("Bonjour " + absent.getNom() + " " + absent.getPrenom() + ", \nVous avez ete absent lors de la seance suivante : \n\nMatiere : " + sc.getMatiere() + "\nDate : " + dateConverted + ".", "text/html" );

                // Send message
                Transport.send(message);
                
             }catch (MessagingException mex) {
                mex.printStackTrace();
             }
            
        }
        flash.success("Les absences ont bien été prises en compte");
        redirect("../../Application/index");
    }
}
